package com.funtl.oauth2.service.impl;

import com.funtl.oauth2.entity.TbPermission;
import com.funtl.oauth2.entity.TbUser;
import com.funtl.oauth2.service.TbPermissionService;
import com.funtl.oauth2.service.TbUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义用户认证与授权
 *
 * @Author: wumz
 * @Date: 2020/8/7 15:53
 * @Version 1.0
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private TbUserService tbUserService;

    @Autowired
    private TbPermissionService tbPermissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //验证用户是否存在
        TbUser user = tbUserService.getUserInfoByName(username);

        //授权参数
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

        if (null != user){
            List<TbPermission> tbPermissions = tbPermissionService.getTbPermissionByUserId(user.getId());
            tbPermissions.forEach(tbPermission -> {
                if (null != tbPermission && null != tbPermission.getEnname()) {
                    grantedAuthorities.add(new SimpleGrantedAuthority(tbPermission.getEnname()));
                }
            });
        }

        return new User(user.getUsername(), user.getPassword(), grantedAuthorities);
    }
}
